package middlewares

import (
	"MyBlogv2/common/HttpCode"
	"MyBlogv2/common/helper"
	"MyBlogv2/common/models"
	"MyBlogv2/common/response"
	"fmt"
	"github.com/gin-gonic/gin"
	"strings"
	"time"
)

// 认证
func AuthUserCheck() gin.HandlerFunc {
	return func(c *gin.Context) {
		const BearerPrefix = "Bearer "
		auth := c.GetHeader("authorization")
		if !strings.HasPrefix(auth, BearerPrefix) {
			c.Abort()
			response.ResponseError(c, HttpCode.NOT_LOGIN)
			return
		}
		auth = strings.TrimPrefix(auth, BearerPrefix)
		fmt.Println("auth:", auth)
		userClaim, err := helper.AnalysisToken(auth)
		if err != nil || userClaim == nil {
			fmt.Println(err)
			fmt.Println("校验出错")
			c.Abort()
			response.ResponseError(c, HttpCode.NOT_LOGIN)
			return

		}
		var user models.User
		models.Db.Model(new(models.User)).Where("id = ?", userClaim.UserId).Find(&user)
		// models.Db.Model(new(models.User)).Where("id = ?", userClaim.UserId).Update("login_time", models.MyTime(time.Now()))

		if user.IsDisAble == 1 {
			c.Abort()
			response.ResponseError(c, HttpCode.BLACK_LIST_ERROR)
			return
		}
		//ip := c.ClientIP()
		//models.Db.Model(new(models.User)).Where("id = ?", userClaim.UserId).Update("login_ip", ip)
		//models.Db.Model(new(models.User)).Where("id = ?", userClaim.UserId).Update("login_time", models.MyTime(time.Now()))
		fmt.Println("userId", userClaim.UserId)
		c.Set("userId", userClaim.UserId)
		c.Next()

	}
}

// 可选认证（不强制要求登录，但如果有token会解析并设置userId）
func OptionalAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		const BearerPrefix = "Bearer "
		auth := c.GetHeader("authorization")
		
		// 如果没有token，直接放行
		if !strings.HasPrefix(auth, BearerPrefix) {
			c.Next()
			return
		}
		
		// 如果有token，尝试解析
		auth = strings.TrimPrefix(auth, BearerPrefix)
		userClaim, err := helper.AnalysisToken(auth)
		if err != nil || userClaim == nil {
			// token无效，但不阻止请求，只是不设置userId
			c.Next()
			return
		}
		
		// 验证用户状态
		var user models.User
		models.Db.Model(new(models.User)).Where("id = ?", userClaim.UserId).Find(&user)
		
		// 如果用户被禁用，也不阻止请求，只是不设置userId
		if user.IsDisAble != 1 {
			c.Set("userId", userClaim.UserId)
			models.Db.Model(new(models.User)).Where("id = ?", userClaim.UserId).Update("login_time", models.MyTime(time.Now()))
		}
		
		c.Next()
	}
}
